<template>
  <div class="jaguar-view">
    <div class="jaguar-search" />
    <div class="jaguar-control">
      <add-button @click="handleCreate" />
    </div>

    <el-card class="jaguar-table">
      <el-table
        :data="tableData"
        v-loading="loading"
        row-key="id"
        default-expand-all
      >
        <el-table-column prop="deptName" label="部门名称" />
        <el-table-column prop="deptLevel" label="部门层级" />
        <el-table-column label="部门主管">
          <template #default="scope">
            <el-tag v-for="manager in scope.row.deptManagers" :key="manager.id">
              {{ manager.userNickName }} ({{ manager.userAccount }})
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="scope">
            <view-button @click="handleView(scope.row)" />
            <edit-button @click="handleEdit(scope.row)" />
            <delete-button
              @confirm="
                ({ instance, done }) =>
                  handleDelete(scope.row, { instance, done })
              "
            />
          </template>
        </el-table-column>
      </el-table>

      <Edit :dialog="dialog" @success="getData()" />
    </el-card>
  </div>
</template>
<script>
import { fetchList, del } from '@/api/upms/dept'
import Edit from './Edit'

export default {
  name: 'Dept',
  data() {
    return {
      loading: false,
      tableData: [],
      dialog: {
        entity: null,
        operation: null,
        visible: false,
      },
    }
  },
  components: {
    Edit,
  },
  created() {
    this.getData()
  },
  methods: {
    getData() {
      this.loading = true
      fetchList()
        .then((res) => {
          this.tableData = res.data.data
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleCreate() {
      this.dialog.entity = null
      this.dialog.depts = this.tableData
      this.dialog.operation = 1
      this.dialog.visible = true
    },
    handleEdit(row) {
      this.dialog.entity = row
      this.dialog.depts = this.tableData
      this.dialog.operation = 2
      this.dialog.visible = true
    },
    handleView(row) {
      this.dialog.entity = row
      this.dialog.depts = this.tableData
      this.dialog.operation = 3
      this.dialog.visible = true
    },
    handleDelete(row, { instance, done }) {
      del(row.id)
        .then(() => {
          done()
          this.$message.success('删除成功')
          this.getData()

          this.$store.dispatch('loginUser/getUserDept')
        })
        .finally(() => {
          instance.confirmButtonLoading = false
        })
    },
  },
}
</script>
